package com.nsyue.auth.config.resources;


import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nsyue.auth.controller.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.nsyue.auth.controller.result.ApiStatusEnum.INVALID_TOKEN;
import static com.nsyue.auth.controller.result.ApiStatusEnum.UNAUTHORIZED;

/**
 * Resource config
 *
 * @author laixm
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Autowired
    private DefaultTokenServices tokenServices;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private AuthExceptionEntryPoint authExceptionEntryPoint;

    @Autowired
    private CustomAccessDeniedHandler customAccessDeniedHandler;

    @Value("${sos.token.header.name:nsyue-sso}")
    private String tokenHeaderName;

    @Value("${spring.application.name:auth-server}")
    private String RESOURCE_ID;


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources
                .tokenExtractor(new CustomTokenExtractor(tokenHeaderName))// 自定义token提取器
                .tokenServices(tokenServices)
                .tokenStore(tokenStore)//令牌存储验证服务，让资源服务自己验证token
                .authenticationEntryPoint(authExceptionEntryPoint)//认证异常处理类
                .accessDeniedHandler(customAccessDeniedHandler)//权限异常处理类
                .resourceId(RESOURCE_ID)//资源ID
                .stateless(true);//会话机制stateless开启
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                // Since we want the protected resources to be accessible in the UI as well we need
                // session creation to be allowed (it's disabled by default in 2.0.6)
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                // 所有以 /api/  开头的 URL属于此资源
                .requestMatchers().antMatchers("/api/**")
                .and()
                .authorizeRequests()
                .antMatchers("/api/**").access("#oauth2.hasScope('read')");

        // 在颁发Authentication时将完整的信息保存到内存，就不需要再进行其他处理了，以下配置废弃。除非需要数据库保存接口权限
        // 为什么要在after
        // 因为OAuth2AuthenticationProcessingFilter.doFilter()包含了SecurityContextHolder.clearContext();
        // http.addFilterAfter(new YeskyAuthenticationFilter(authenticationManager, tokenStore, tokenHeaderName), AbstractPreAuthenticatedProcessingFilter.class);
    }

    @Component
    public static class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response,
                             AuthenticationException authException) throws ServletException {
            Throwable cause = authException.getCause();
            Throwable throwable = authException.fillInStackTrace();
            response.setStatus(HttpStatus.OK.value());
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            try {
                response
                        .getWriter()
                        .write(JSONUtil.toJsonStr(Result.failed(INVALID_TOKEN)));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Component
    public static class CustomAccessDeniedHandler implements AccessDeniedHandler {

        @Override
        public void handle(HttpServletRequest request, HttpServletResponse response,
                           AccessDeniedException accessDeniedException)
                throws IOException, ServletException {
            response.setStatus(HttpStatus.OK.value());
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            try {
                Result<?> result = Result.failed(UNAUTHORIZED);
                response.getWriter().write(new ObjectMapper().writeValueAsString(result));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



}

